<?php

namespace App\Console\Commands\Deploy;

use App\Models\RepoSetting;
use Illuminate\Console\Command;

class ClearLocal extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'deploy:clear-local';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '清除本地源码';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $repo_base_path = '/data/deploy/storage/repositories/';
        RepoSetting::whereNotNull('last_sha_id')->where('id', '>', 1)->get()->each(function (RepoSetting $repo) use ($repo_base_path) {
            preg_match('/\.com:2222\/(.*)\.git/', $repo->repo_url, $matches);
            $repo = $repo_base_path . $matches[1];
            if (is_dir($repo)) {
                $files = glob($repo . '/*');

                $sorted_files = [];
                foreach ($files as $file) {
                    $sorted_files[filemtime($file)] = $file;
                }

                ksort($sorted_files);
                array_pop($sorted_files);
                foreach ($sorted_files as $file) {
                    if ($file && strpos($file, $repo_base_path) === 0) {
                        `rm -rf $file`;
                        $this->info('[' . $file . '] deleted.');
                    }
                }
            } else {
                $this->warn('[' . $repo . '] is not dir, skipped.');
            }
        });
    }
}
